﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using Abp;
using Abp.Dependency;
using Abp.Reflection;
using Abp.Threading.BackgroundWorkers;
using KelonProud.BackgroundJobs.Jobs.Base;
using KelonProud.BackgroundJobs.Workers;

namespace KelonProud.BackgroundJobs.Core
{
    public class JobInitialize:ISingletonDependency
    {
        private readonly ITypeFinder _typeFinder;

        public JobInitialize(ITypeFinder typeFinder)
        {
            _typeFinder = typeFinder;
        }

        public void Init()
        {
            InitWorker();

            InitCronJob();

            //InitScheduleJob();

            //InitSigleJob();
        }

        private  void InitWorker()
        {
            var workManager = IocManager.Instance.Resolve<IBackgroundWorkerManager>();

            var workers = _typeFinder.Find(type => type.IsSubclassOf(typeof(PeriodicBackgroundWorkerBase)));

            workers.Each(e =>
            {
                workManager.Add((PeriodicBackgroundWorkerBase)IocManager.Instance.Resolve(e));
            });

        }

        private  void InitCronJob()
        {
            var jobs = _typeFinder.Find(type => type.IsSubclassOf(typeof(CronJobBase)));

            jobs.Each(e =>
            {
                if (!e.IsAbstract)
                {
                    ((CronJobBase)IocManager.Instance.Resolve(e)).Init();
                }
            });
        }

        //private  void InitSigleJob()
        //{
        //    var jobs = _typeFinder.Find(type => type.IsSubclassOf(typeof(SigleJobBase)));

        //    jobs.Each(e =>
        //    {
        //        ((SigleJobBase)IocManager.Instance.Resolve(e)).Init();
        //    });
        //}

        //private  void InitScheduleJob()
        //{
        //    var jobs = _typeFinder.Find(type => type.IsSubclassOf(typeof(ScheduleJobBase)));

        //    jobs.Each(e =>
        //    {
        //        ((ScheduleJobBase)IocManager.Instance.Resolve(e)).Init();
        //    });
        //}
    }
}
